package com.coriander.chatglm.domain.openai.service;

import cn.bugstack.chatglm.session.OpenAiSession;
import com.coriander.chatglm.domain.openai.model.aggregates.ChatProcessAggregate;
import com.coriander.chatglm.types.common.Constants;
import com.coriander.chatglm.types.exception.ChatGPTException;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;

/**
 * @Author YaoBoning
 * @Date 2024/12/6 14:59
 * @Description 抽象对话服务类
 */
@Slf4j
public abstract class AbstractChatService implements IChatService{

    @Resource
    protected OpenAiSession openAiSession;
    @Override
    public ResponseBodyEmitter completions(ChatProcessAggregate chatProcessAggregate) {
        // 1. 校验权限
        if(!"coriander1104".equals(chatProcessAggregate.getToken())) {
            throw new ChatGPTException(Constants.ResponseCode.TOKEN_ERROR.getCode(), Constants.ResponseCode.TOKEN_ERROR.getInfo());
        }

        // 2. 请求应答
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(3*60*1000L);
        emitter.onCompletion(() -> {
            log.info("流式问答请求完成, 使用模型 {}", chatProcessAggregate.getModel());
        });

        emitter.onError(throwable -> {
            log.error("流式问答请求错误, 使用模型 {}", chatProcessAggregate.getModel(), throwable);
        });

        // 3. 应答处理
        try {
            this.doMessageResponse(chatProcessAggregate, emitter);
        } catch (Exception e) {
            throw new ChatGPTException(Constants.ResponseCode.UN_ERROR.getCode(), Constants.ResponseCode.UN_ERROR.getInfo(), e);
        }
        // 4. 返回结果
        return null;
    }

    protected abstract void doMessageResponse(ChatProcessAggregate chatProcessAggregate, ResponseBodyEmitter emitter) throws JsonProcessingException;
}
